﻿using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-06-21 15:32
    /// 描 述：信号服务层
    /// </summary>
    public class ec_Wire_GroupService
    {
        #region 仓储
        public Repository<ec_Wire_GroupEntity> _wireGroupRepository => new Repository<ec_Wire_GroupEntity>();
        #endregion
        #region 获取数据

        public ec_Wire_GroupEntity GetEntity(string ProjectId, string keyValue)
        {
            try
            {
                var tableName = ProjectSugar.TableName<ec_Wire_GroupEntity>(ProjectId);
                return _wireGroupRepository.AsQueryable().AS(tableName).Single(x => x.Wire_Group_ID == keyValue);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        public List<ec_Wire_Group_TemplateEntity> GetTemplateList(string ProjectId)
        {
            var tableName = ProjectSugar.TableName<ec_Wire_Group_TemplateEntity>(ProjectId);
            return SqlSugarHelper.Db.Queryable<ec_Wire_Group_TemplateEntity>().AS(tableName).OrderBy(x => x.OrderID).ToList();
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string ProjectId, string WireGroupID)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                var Proj = SqlSugarHelper.Db.Queryable<ec_projectEntity>().Single(x => x.ProjectId == ProjectId);
                if (Proj == null) { return; }
                var tableName = ProjectSugar.TableName<ec_Wire_GroupEntity>(Proj.ProjectIndex.ToString());
                SqlSugarHelper.Db.Updateable<ec_Wire_GroupEntity>().AS(tableName).Where(x => x.Wire_Group_ID == WireGroupID).SetColumns(x => x.DeleteFlg == true).ExecuteCommand();

                tableName = ProjectSugar.TableName<ec_wire_group_noticeEntity>(Proj.ProjectIndex.ToString());
                SqlSugarHelper.Db.Deleteable<ec_wire_group_noticeEntity>().AS(tableName).Where(x => x.WireGroupID == WireGroupID).ExecuteCommand();

                tableName = ProjectSugar.TableName<ec_wire_group_propertyhisEntity>(Proj.ProjectIndex.ToString());
                SqlSugarHelper.Db.Deleteable<ec_wire_group_propertyhisEntity>().AS(tableName).Where(x => x.WireGroupID == WireGroupID).ExecuteCommand();

                tableName = ProjectSugar.TableName<ec_wire_group_logEntity>(Proj.ProjectIndex.ToString());
                SqlSugarHelper.Db.Deleteable<ec_wire_group_logEntity>().AS(tableName).Where(x => x.WireGroupID == WireGroupID).ExecuteCommand();


                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 比较更新前后的差异值。同时写入his
        /// </summary>
        /// <returns></returns>
        public string CompareModifyField(string ProjIndex, ec_Wire_GroupEntity Old, ec_Wire_GroupEntity New, string ignoreCols = "")
        {
            var tableName = ProjectSugar.TableName<ec_wire_group_propertyhisEntity>(ProjIndex);
            var res = "";
            var PropDefs = typeof(ec_Wire_GroupEntity).GetProperties();
            var lists = new List<ec_wire_group_propertyhisEntity>();
            foreach (PropertyInfo PropDef in PropDefs)
            {
                if (PropDef.Name.ToUpper() == "CREATETIME" || PropDef.Name.ToUpper() == "UPDATETIME" || PropDef.Name.ToUpper() == "UPDATEUSERID" || PropDef.Name.ToUpper() == "CREATEUSERID")
                {
                    continue;
                }
                if (PropDef.Name.ToUpper() == "PANELID" || PropDef.Name.ToUpper() == "STRIPID" || PropDef.Name.ToUpper() == "CHANNELID" || PropDef.Name.ToUpper() == "WIREGROUPTEMPLATEID")
                {
                    continue;
                }
                if (ignoreCols.ToUpper().Split(',').Contains(PropDef.Name.ToUpper()))
                {
                    continue;
                }
                var Attr = PropDef.GetCustomAttribute(typeof(SugarColumn));
                if (Attr != null)
                {
                    if (((SugarColumn)Attr).IsIgnore == true)
                    {
                        continue;
                    }
                }
                string OldValue = PropDef.GetValue(Old, null)?.ToString();
                string NewValue = PropDef.GetValue(New, null)?.ToString();
                if (OldValue != NewValue)
                {
                    if (string.IsNullOrEmpty(OldValue) && string.IsNullOrEmpty(NewValue))
                    {
                        continue;
                    }

                    res += $"属性【{PropDef.Name}】由【{OldValue}】改为【{NewValue}】。\n";
                    var x = new ec_wire_group_propertyhisEntity()
                    {
                        NewPropertyValue = NewValue,
                        OldPropertyValue = OldValue,
                        PropertyName = PropDef.Name,
                        WireGroupID = Old.Wire_Group_ID
                    };
                    x.Create();
                    lists.Add(x);
                }
            }
            SqlSugarHelper.Db.Insertable(lists).AS(tableName).ExecuteCommand();
            return res;
        }
        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string ProjectId, string WireGroupID, ec_Wire_GroupEntity entity, string mode = "0")
        {
            try
            {
                Console.WriteLine(entity.CableName);
                var tableName = ProjectSugar.TableName<ec_Wire_GroupEntity>(ProjectId);
                //entity.Group_Name = entity.Signal_Group + entity.Signal_SeqNo;
                if (!string.IsNullOrEmpty(WireGroupID))
                {
                    entity.Modify(WireGroupID);
                    if (mode == "0")
                    {

                        _wireGroupRepository.AsUpdateable(entity).AS(tableName).
                            IgnoreColumns(x => x.CreateTime).
                            IgnoreColumns(x => x.CreateUserID).
                            IgnoreColumnsIF(!string.IsNullOrEmpty(ProjectId), x => x.WireGroupTemplateID).
                            ExecuteCommand();
                    }
                    else
                    {
                        //从IO关联界面进来，只负责更新channelid这几列。BUG 3328，这样不至于在自动化平台修改后（如描述），再保存IO关联界面，数据又回去了。
                        _wireGroupRepository.AsUpdateable(entity).AS(tableName).
                           UpdateColumns(x => x.ChannelID).
                           UpdateColumns(x => x.UpdateUserID).
                           UpdateColumns(x => x.UpdateTime).
                           ExecuteCommand();
                    }
                    //遍历属性，来插入历史记录(特定流程的不在这里，比如关联后修改属性）
                    if (true)
                    {

                    }
                }
                else
                {
                    entity.Create();
                    _wireGroupRepository.AsInsertable(entity).AS(tableName).ExecuteCommand();
                    WireGroupID = entity.Wire_Group_ID;
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        #endregion

    }
}
